using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Users.Roles;

namespace Team.API.Applocation.Handler.Users.Roles
{
    /// <summary>
    /// 更新角色处理器
    /// </summary>
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, APIResult<RoleDTO>>
    {
        private readonly IRepository<Rolemodel> roleRepository;

        public UpdateRoleHandler(IRepository<Rolemodel> roleRepository)
        {
            this.roleRepository = roleRepository;
        }

        public async Task<APIResult<RoleDTO>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            // 查询角色是否存在
            var role = await roleRepository.GetByIdAsync(request.Id);
            if (role == null || role.IsDel)
            {
                return APIResult<RoleDTO>.Faile("角色不存在");
            }

            // 检查是否为系统内置角色

            // 更新角色信息（只更新非空字段）
            if (!string.IsNullOrWhiteSpace(request.RoleName))
            {
                role.RoleName = request.RoleName.Trim();
            }

            if (request.Description != null)
            {
                role.Description = request.Description;
            }

            if (request.Status.HasValue)
            {
                role.Status = request.Status.Value;
            }

            if (request.RoleType.HasValue)
            {
                role.RoleType = request.RoleType.Value;
            }

            if (request.Remark != null)
            {
                role.Remark = request.Remark;
            }

            // 更新审计信息
            //role.Updatedate = DateTime.Now;
            //role.Updatename = "系统管理员"; // TODO: 从当前登录用户获取

            int rows = await roleRepository.UpdateAsync(role);
            if (rows <= 0)
            {
                return APIResult<RoleDTO>.Faile("更新角色失败");
            }

            // 构造返回DTO
            var dto = new RoleDTO
            {
                Id = role.Id,
                RoleCode = role.RoleCode,
                RoleName = role.RoleName,
                Description = role.Description,
                Status = role.Status,
                RoleType = role.RoleType,
                Remark = role.Remark,
                //UpdateDate = role.Updatedate,
                //UpdateName = role.Updatename
            };

            return APIResult<RoleDTO>.Ok("更新角色成功", dto);
        }
    }
}
